package core 
{
	import event.ActionEvent;
	import event.ViewEvent;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import util.ShareEvent;
	import util.UiCopyUtil;
	
	/**
	 * ...
	 * @author liwei
	 */
	[Event(name="viewinit", type="event.ViewEvent")]
	public class ViewBase extends Sprite 
	{
		private var _viewLoader:Loader;
		protected var _ui:DisplayObject;
		public function ViewBase() 
		{
			super();
		}
		public function load(src:String):void {
			if (_viewLoader == null) {
				_viewLoader = new Loader();
				addChild(_viewLoader);
				_viewLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, viewLoader_complete);
				_viewLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, viewLoader_ioError);
				_viewLoader.load(new URLRequest(src), new LoaderContext(false, ApplicationDomain.currentDomain));
				_viewLoader.contentLoaderInfo.sharedEvents.addEventListener(DataEvent.DATA, sharedEvents_data);
			}
		}
		
		private function sharedEvents_data(e:DataEvent):void 
		{
			ShareEvent.dispatchEvent(new ActionEvent(ActionEvent.ACTION, e.data));
		}
		protected function loadInit():void {
			
		}
		protected function loadError():void {
			
		}
		protected function getUI(name:String):*{
			return _ui[name];
		}
		private function viewLoader_ioError(e:IOErrorEvent):void 
		{
			removeEvent();
			loadError();
		}
		private function removeEvent():void {
			_viewLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, viewLoader_complete);
			_viewLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, viewLoader_ioError);
		}
		private function viewLoader_complete(e:Event):void 
		{
			removeEvent();
			removeChild(_viewLoader);
			_ui = _viewLoader.content;
			UiCopyUtil.copy(_ui, this);
			addChild(_ui);
			loadInit();
			dispatchEvent(new ViewEvent(ViewEvent.INIT));
		}
	}

}